package com.itany.controllers;

import com.itany.service.NoticeService;
import com.itany.vo.ActionResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/notice")
public class NoticeController {
    @Autowired
    NoticeService service;

    @RequestMapping("/findAll")
    public Map<String,Object> getData(
            @RequestParam(name = "page",defaultValue = "1") Integer page,
            @RequestParam(name = "rows",defaultValue = "10") Integer rows){
        Map<String,Object> map = new HashMap<String,Object>();
        List<Map<String,Object>> list = service.queryAll();
        int total = list != null ? list.size() : 0;

        // 如果总数据量小于或等于每页显示的数据条数，则始终从第一页开始，且只显示一页
        if (total <= rows) {
            page = 1;
        } else {
            // 计算总页数，并检查请求的页码是否超出范围
            int totalPages = (int) Math.ceil((double) total / rows);
            if (page > totalPages) {
                page = 1; // 如果请求的页码大于总页数，则重置为第一页
            }
        }

        // 计算起始和结束索引
        int startIndex = (page - 1) * rows;
        int endIndex = Math.min(startIndex + rows, total);

        // 创建结果列表，并填充数据
        if(list!=null){
            List<Map<String, Object>> ref = list.subList(startIndex, endIndex);
            map.put("rows", ref);
        }else{
            map.put("rows",0);
        }

        map.put("total", total);

        return map;
    }

    @RequestMapping("/delete")
    public ActionResult delete(@RequestParam("id") Integer id){
        service.deleteById(id);
        return ActionResult.success("删除成功!",200,null);
    }

    @RequestMapping("/add")
    public ActionResult add(@RequestParam("title") String title,@RequestParam("info") String info,@RequestParam("manageruserid") Integer manageruserid){
        service.insert(title, info, manageruserid);
        return ActionResult.success("提交成功!",200,null);
    }
}
